package com.summer.framework.core.thread;

import com.alibaba.ttl.threadpool.TtlExecutors;

import java.util.concurrent.*;

/**
 * Description: 线程池管理，简单使用一个静态工具类使用，
 * 自身可以根据项目情况，可以定义不同类型（io密集型，cpu密集型）的线程池，注入到spring 容器中
 * @auther Ice Yang
 * Date 2025/7/2 16:49
 */
public class SummerThreadPools {
    private static ExecutorService executor = null;

    private SummerThreadPools() {
    }

    public static ExecutorService getExecutor() {
        checkExecutor();
        return executor;
    }

    public static void execute(Runnable task) {
        checkExecutor();
        if (task != null) {
            executor.execute(task);
        }
    }

    public static <T> Future<T> submit(Callable<T> task) {
        checkExecutor();
        if (task != null) {
            return executor.submit(task);
        } else {
            return null;
        }
    }

    public static <T> T submitAndReturnValue(Callable<T> task) throws ExecutionException, InterruptedException {
        checkExecutor();
        if (task != null) {
            Future<T> future = executor.submit(task);
            return future.get();
        }
        return null;
    }

    public static void shutdown() {
        if (executor != null) {
            executor.shutdown();
        }
    }

    public static void shutdownNow() {
        if (executor != null) {
            executor.shutdownNow();
        }

    }

    private static void checkExecutor() {
        if (executor == null || executor.isShutdown()) {
            synchronized (SummerThreadPools.class) {
                if (executor == null || executor.isShutdown()) {
                    int cores = Runtime.getRuntime().availableProcessors();
                    executor = TtlExecutors.getTtlExecutorService(
                            new ThreadPoolExecutor(cores, cores + 1, 60L,
                                    TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100),
                                    new ThreadPoolExecutor.DiscardOldestPolicy()));
                }
            }
        }
    }
}
